var th = null;
var isAnimation = "default";
let StudentAboutClass = null;

$(window).ready(function(){
    sessionStorage.setItem('flag', 'default');
    updateClassTypeList();
    InitData();
});

// 切换周功能
$("#prev-button").on("click",function(){
    $("#Class_table_1 .table_time th").text(getFormattedWeekDate($("#Class_table_1 .table_time th").text(),-1));
    sessionStorage.setItem('flag', 'false');
    isAnimation = "translateX(-100%)";
    $(".course").empty();
    InitData();
});

$("#next-button").on("click",function(){
    $("#Class_table_1 .table_time th").text(getFormattedWeekDate($("#Class_table_1 .table_time th").text(),1));
    sessionStorage.setItem('flag', 'true');
    isAnimation = "translateX(100%)";
    $(".course").empty();
    InitData();
});

// 课程安排右击事件
$(".course").on("contextmenu", function(e){
    // 阻止默认的右键菜单弹出
    e.preventDefault();
    var className = $(this).find("span").eq(0).text();
    var coachName = $(this).find("span").eq(1).text();
    var id = $(this).find("span").eq(2).text();
    var site = $(this).find("span").eq(3).text();
    var date = $(this).parent().find("th").eq(0).text();
    th = $(this);
    var mouseX = e.pageX;
    var mouseY = e.pageY;

    // 移除可能已存在的上下文菜单
    $('.context-menu').remove();

    // 创建上下文菜单
    var contextMenu = $('<div class="context-menu">')
        .css({
            position: 'absolute',
            top: mouseY,
            left: mouseX,
            background: '#fff',
            border: '1px solid #ccc',
            boxShadow: '2px 2px 5px rgba(0,0,0,0.2)',
            padding: '5px 0',
            zIndex: 1000
        })
        .append(
            $('<div class="menu-item">').text('编辑课程').css({
                padding: '8px 20px',
                cursor: 'pointer',
                'hover': {
                    background: 'red'
                }
            }),
            $('<div class="menu-item">').text('删除课程').css({
                padding: '8px 20px',
                cursor: 'pointer',
                'hover': {
                    background: '#f0f0f0'
                }
            })
        );

    // 将菜单添加到body
    $('body').append(contextMenu);

    // 点击其他地方时移除菜单
    $(document).on('click', function() {
        contextMenu.remove();
    });

    // 为菜单项
    contextMenu.find('.menu-item').on('click', function(e) {
        e.stopPropagation();
        var action = $(this).text();
        // 根据不同的菜单项执行相应的操作
        switch(action) {
            case '编辑课程':
                $("#addCourseScheduleModal #addCourseScheduleModalLabel").html("编辑课程安排");
                showAddCourseScheduleModal(date,className,coachName,id,site);
                break;
            case '删除课程':
                // 添加删除课程的逻辑
                alert("删除课程")
                break;
        }
        contextMenu.remove();
    });
  });

// 添加课程安排点击事件
$("#term-7").on("click", ".class", function(){
    var class_name = $(this).find("span").eq(0).text();
    var coach_name = $(this).find("span").eq(1).text();
    var id = $(this).find("span").eq(2).text();
    var site = $(this).find("span").eq(3).text();
    var date = $(this).parent().find("th").eq(0).text();
    $("#addCourseScheduleModal #addCourseScheduleModalLabel").html("新增课程安排");
    // 显示模态框
    showAddCourseScheduleModal(date,class_name,coach_name,id,site);
});

// 模态框保存按钮点击事件
$("#addCourseScheduleModal").on("click",".btn-primary",function (){
    let coach_name = $("#addCourseScheduleModal").find("#courseInstructor").val();
    let class_name = $("#addCourseScheduleModal").find("#courseName").val();
    let time = $("#addCourseScheduleModal").find("#courseTime").val();
    let id = $("#addCourseScheduleModal").find("#courseId").val(); // 设置隐藏的ID
    let site = $("#addCourseScheduleModal").find("#courseLocation").val();
    let Stuarray = [];
   if (StudentAboutClass) {
        StudentAboutClass.forEach(student => {
            Stuarray.push(student.value);
        });
    } else {
        // 处理数组为空的情况
    }
    if($("#addCourseScheduleModal #addCourseScheduleModalLabel").html() == "新增课程安排"){
        $.ajax("../AddSched",{
            type:"post",
            async:false,
            data:{
                classType:$("#term-7 .form-control").val(),
                weekOfMonth:$("#term-7 .table_time th").text(),
                ClassName:class_name,
                CoachName:coach_name,
                time:time,
                site:site,
                id:id,
                StudentId:Stuarray.toString(),
            },
            success:function (data){
                th.find("span").eq(0).text(class_name);
                th.find("span").eq(1).text(coach_name);
                th.find("span").eq(2).text(id);
                th.find("span").eq(3).text(site);
                $("#addCourseScheduleModal").modal("hide");
            }
        })
    }else{
        $.ajax("../UpdataClass",{
            type:"post",
            async:false,
            data:{
                classType:$("#term-8 .form-control").val(),
                weekOfMonth:$("#term-8 .table_time th").text(),
                ClassName:class_name,
                CoachName:coach_name,
                time:time,
                site:site,
                id:id,
                StudentId:Stuarray.toString(),
            },
            success:function (data){
                th.find("span").eq(0).text(class_name);
                th.find("span").eq(1).text(coach_name);
                th.find("span").eq(2).text(id);
                th.find("span").eq(3).text(site);
                $("#addCourseScheduleModal").modal("hide");
            }
        });
    }

});
//模态框显示函数
function showAddCourseScheduleModal(time,class_name,coach_name,id,site){
    if(coach_name == ""){
        coach_name = "请选择教练";
    }
    if(class_name == ""){
        class_name = "请输入课程名称";
    }

    // 设置模态框中的值
    $("#addCourseScheduleModal").find("#courseInstructor").val(coach_name);
    $("#addCourseScheduleModal").find("#courseName").val(class_name);
    $("#addCourseScheduleModal").find("#courseTime").val(time);
    $("#addCourseScheduleModal").find("#courseId").val(id); // 设置隐藏的ID
    $("#addCourseScheduleModal").find("#courseLocation").val(site);
    $("#addCourseScheduleModal").modal("show");
    $.ajax("../ListStuAboutClass",{
        type:"post",
        async:false,
        data:{
            id:id,
            time:time
        },
        success:function (data){
            InitStu(data.studentList,data.list);
        }
    })
}

function InitData(){
    $.ajax("../ListClass",{
        type:"post",
        data:{
            classType:$("#term-8 .form-control").val(),
            weekOfMonth:$("#term-8 .table_time th").text(),
        },
        success:function (data){
            if(data.message == "获取数据失败"){
                $("#term-8 .table-responsive tbody tr .course").empty();
                initAnimation();
            }else{
                ListClass(data.classList);//列出所有课程
                getCochesName(data.classCoaches);//列出所有教练的名字
                ListAllName(data.ClassAll);//列出所有课程名称
                initAnimation();
            }
        }
    })
}
//初始化穿梭框-于一课学生录
function InitStu(data, SelectedStu) {
    // 初始化穿梭框
    layui.use(['transfer'], function() {
        var transfer = layui.transfer;

        // 格式化学生数据
        let studentData = data.map(student => ({
            value: student.stuId,
            title: student.stuName,
        }));

        // 从 studentData 中移除 SelectedStu 中的项

        let array = [];
        SelectedStu.forEach(student => {
            array.push(student.stuId);
        })
        // 初始化穿梭框
        transfer.render({
            elem: '#ID-transfer-demo-showSearch',
            data: studentData,
            value:array,
            title: ['待选学生', '已选学生'],
            showSearch: true,
            width: '100%',  // 使用100%宽度
            height: 400,
            id: 'studentTransfer',
            text: {
                none: '无数据',
                searchNone: '无匹配数据'
            },
            onchange: function(data, index) {
                // 获取所有已选学生
                StudentAboutClass = transfer.getData('studentTransfer');
            }
        });
    });
}

function addOptionIfNotExists(selectElement, optionValue) {
    var exists = false;
    $(selectElement + ' option').each(function() {
        if ($(this).val() === optionValue) {
            exists = true;
            return false;
        }
    });
    if (!exists) {
        $(selectElement).append($('<option>').text(optionValue));
    }
}
function ListAllName(data){
    $("#addCourseScheduleModal #courseName").empty();
    for(let i = 0;i<5;i++){
        var data1_first = JSON.parse(data[i].firstClass);
        var data1_second = JSON.parse(data[i].secondClass);
        var data1_third = JSON.parse(data[i].thirdClass);
        var data1_forth = JSON.parse(data[i].fourthClass);
        addOptionIfNotExists("#addCourseScheduleModal #courseName", data1_first.class);
        addOptionIfNotExists("#addCourseScheduleModal #courseName", data1_second.class);
        addOptionIfNotExists("#addCourseScheduleModal #courseName", data1_third.class);
        addOptionIfNotExists("#addCourseScheduleModal #courseName", data1_forth.class);
    }
}

function updateClassTypeList() {
    $.ajax("../ListClassType",{
        type:"post",
        success:function (data) {
            // 更新下拉列表
            var classTypeSelect = $("#term-8 .form-control");
            classTypeSelect.empty(); // 清空现有的选项
            data.forEach(function (classType) {
                classTypeSelect.append($('<option>').text(classType));
            });
        }
    });
}

function ListClass(data){
        $("#term-8 #Class_table_1 .table_time th").html(data[0].weekOfMonth);
        for(let i = 0;i<5;i++){
            var data1_first = JSON.parse(data[i].firstClass);
            var data1_second = JSON.parse(data[i].secondClass);
            var data1_third = JSON.parse(data[i].thirdClass);
            var data1_forth = JSON.parse(data[i].fourthClass);
            $(".course").eq(i).html("<span>"+data[i].weekDay+"</span>/<span>"+data[i].time+"</span>");
            $(".course").eq(i+5).html("<span>"+data1_first.class+"</span><br/><span>"+data1_first.teacher+"</span><span style='display: none'>"+data[i].classId+"</span><span style='display: none'>"+data1_first.site+"</span>");
            $(".course").eq(i+10).html("<span>"+data1_second.class+"</span><br/><span>"+data1_second.teacher+"</span><span style='display: none'>"+data[i].classId+"</span><span style='display: none'>"+data1_second.site+"</span>");
            $(".course").eq(i+15).html("<span>"+data1_third.class+"</span><br/><span>"+data1_third.teacher+"</span><span style='display: none'>"+data[i].classId+"</span><span style='display: none'>"+data1_third.site+"</span>");
            $(".course").eq(i+20).html("<span>"+data1_forth.class+"</span><br/><span>"+data1_forth.teacher+"</span><span style='display: none'>"+data[i].classId+"</span><span style='display: none'>"+data1_forth.site+"</span>");
        }
}
//表格切换动画
function initAnimation(){
     // 设置初始位置，禁用过渡
     $("#term-8 table").css({
        transition: 'none',  // 禁用过渡
        transform: isAnimation,
        opacity: 0
    });

    // 强制浏览器重绘，确保过渡被禁用
    $("#term-8 table")[0].offsetHeight;

    // 开始动画，启用过渡
    $("#term-8 table").css({
        transition: 'transform 0.5s ease-out, opacity 0.5s ease-out',  // 启用过渡
        transform: 'translateX(0)',
        opacity: 1
    });
}

//切换周功能
function getFormattedWeekDate(dateStr, offset) {
     // 解析传入的日期字符串
     let [year, month, weekStr] = dateStr.match(/(\d+)年(\d+)月第(\d+)周/).slice(1).map(Number);
        
     // 计算目标周的开始日期
     let totalWeeks = (month - 1) * 5 + weekStr + offset;
     let newMonth = Math.ceil(totalWeeks / 5);
     let newWeek = totalWeeks % 5 || 5;
     let newYear = year + Math.floor((newMonth - 1) / 12);
     
     if (newMonth <= 0) {
         newMonth += 12;
         newYear -= 1;
     } else {
         newMonth = (newMonth - 1) % 12 + 1;
     }
     
     return newYear + '年' + newMonth + '月第' + newWeek + '';
}

$("#addCourseModal .btn-primary").on("click", function() {
    // 获取输入框中的值
    let courseName = $("#newCourseName").val();
    let courseDescription = $("#newCourseDescription").val();
   $.ajax("../AddClassType",{
        type:"post",
        data:{
            classType:courseName,
            classDescription:courseDescription,
        },
        success:function (data){
            var classTypeSelect = $("#term-8 .form-control");
            var classTypeSelect2 = $("#term-7 .form-control");
            classTypeSelect.append($('<option>').text(courseName));
            classTypeSelect2.append($('<option>').text(courseName));
        }
   })
    $("#addCourseModal").modal("hide");
});

$("#term-8 .form-control").on("change",function (){
    InitData();
});

// 打印报表
function printTable() {
    var print = document.getElementById('Class_table_1').innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = print;
    window.print();
    //窗口刷新
    window.location.reload();
    document.body.innerHTML = originalContents;
}

// 获取教练列表
function getCochesName(data) {
    if(data && data.length > 0) {
        // 清空现有选项
        $("#courseInstructor").empty();
        // 添加默认选项
        $("#courseInstructor").append('<option value="">请选择教练</option>');

        // 添加教练选项
        data.forEach(coach => {
            $("#courseInstructor").append(
                `<option>
                    ${coach}
                 </option>`
            );
        });
    }
}

$(document).ready(function() {
    const changeRequests = [
        { studentName: "张三", originalCourse: "数学", originalCoach: "李教练", originalTime: "周一 10:00", originalLocation: "教室A", requestedCourse: "物理", requestedCoach: "王教练", requestedTime: "周三 14:00", requestedLocation: "教室B", status: "待审批", applicationTime: "2023-10-01T10:00:00" },
        { studentName: "李四", originalCourse: "英语", originalCoach: "王教练", originalTime: "周二 11:00", originalLocation: "教室C", requestedCourse: "化学", requestedCoach: "张教练", requestedTime: "周四 15:00", requestedLocation: "教室D", status: "已批准", applicationTime: "2023-10-02T11:30:00" },
        { studentName: "王五", originalCourse: "历史", originalCoach: "赵教练", originalTime: "周三 09:00", originalLocation: "教室E", requestedCourse: "地理", requestedCoach: "钱教练", requestedTime: "周五 16:00", requestedLocation: "教室F", status: "待审批", applicationTime: "2023-10-03T09:00:00" },
        { studentName: "赵六", originalCourse: "化学", originalCoach: "孙教练", originalTime: "周四 14:00", originalLocation: "教室G", requestedCourse: "生物", requestedCoach: "李教练", requestedTime: "周六 10:00", requestedLocation: "教室H", status: "已批准", applicationTime: "2023-10-04T14:00:00" },
        { studentName: "钱七", originalCourse: "物理", originalCoach: "周教练", originalTime: "周五 11:00", originalLocation: "教室I", requestedCourse: "数学", requestedCoach: "吴教练", requestedTime: "周日 13:00", requestedLocation: "教室J", status: "待审批", applicationTime: "2023-10-05T11:00:00" },
        { studentName: "孙八", originalCourse: "生物", originalCoach: "郑教练", originalTime: "周六 15:00", originalLocation: "教室K", requestedCourse: "化学", requestedCoach: "王教练", requestedTime: "周一 08:00", requestedLocation: "教室L", status: "已批准", applicationTime: "2023-10-06T15:00:00" },
        { studentName: "李九", originalCourse: "地理", originalCoach: "王教练", originalTime: "周日 10:00", originalLocation: "教室M", requestedCourse: "历史", requestedCoach: "赵教练", requestedTime: "周二 14:00", requestedLocation: "教室N", status: "待审批", applicationTime: "2023-10-07T10:00:00" },
        { studentName: "周十", originalCourse: "英语", originalCoach: "钱教练", originalTime: "周一 09:00", originalLocation: "教室O", requestedCourse: "物理", requestedCoach: "孙教练", requestedTime: "周三 15:00", requestedLocation: "教室P", status: "已批准", applicationTime: "2023-10-08T09:00:00" }
    ];

    let currentPage = 1;
    const itemsPerPage = 5;

    function renderPage(page) {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const paginatedItems = changeRequests.slice(start, end);

        renderChangeRequests(paginatedItems);
        $("#pageInfo").text(`第 ${page} 页，共 ${Math.ceil(changeRequests.length / itemsPerPage)} 页`);
    }

    function sortChangeRequestsByTime(changeRequests, isAscending) {
        changeRequests.sort((a, b) => {
            return isAscending ? new Date(a.applicationTime) - new Date(b.applicationTime) : new Date(b.applicationTime) - new Date(a.applicationTime);
        });

        renderPage(1); // 重新渲染第一页
    }

    function sortChangeRequestsByStatus(changeRequests, isAscending) {
        changeRequests.sort((a, b) => {
            return isAscending ? a.status.localeCompare(b.status) : b.status.localeCompare(a.status);
        });

        renderPage(1); // 重新渲染第一页
    }

    $("#prevPage").on("click", function() {
        if (currentPage > 1) {
            currentPage--;
            renderPage(currentPage);
        }
    });

    $("#nextPage").on("click", function() {
        if (currentPage < Math.ceil(changeRequests.length / itemsPerPage)) {
            currentPage++;
            renderPage(currentPage);
        }
    });

    renderPage(currentPage);

    let isAscendingTime = true;
    $("#sortByApplicationTime").on("click", function() {
        sortChangeRequestsByTime(changeRequests, isAscendingTime);
        isAscendingTime = !isAscendingTime;

        const icon = $(this).find("i");
        icon.toggleClass("fa-sort-up", isAscendingTime);
        icon.toggleClass("fa-sort-down", !isAscendingTime);
    });

    let isAscendingStatus = true;
    $("#sortByStatus").on("click", function() {
        sortChangeRequestsByStatus(changeRequests, isAscendingStatus);
        isAscendingStatus = !isAscendingStatus;

        const icon = $(this).find("i");
        icon.toggleClass("fa-sort-up", isAscendingStatus);
        icon.toggleClass("fa-sort-down", !isAscendingStatus);
    });
});

function renderChangeRequests(changeRequests) {
    $("#change-request-table-body").empty();
    changeRequests.forEach(request => {
        var tr = $("<tr></tr>");
        tr.append("<td>" + request.studentName + "</td>")
          .append("<td>" + formatCourseInfo(request.originalCourse, request.originalCoach, request.originalTime, request.originalLocation) + "</td>")
          .append("<td>" + formatCourseInfo(request.requestedCourse, request.requestedCoach, request.requestedTime, request.requestedLocation) + "</td>")
          .append("<td>" + request.applicationTime.replace("T", " ") + "</td>")
          .append("<td>" + request.status + "</td>");

        if (request.status !== "已批准") {
            tr.append("<td><button class='btn btn-sm btn-info'>批准</button></td>");
        } else {
            tr.append("<td><button class='btn btn-sm btn-secondary' disabled>已批准</button></td>");
        }

        $("#change-request-table-body").append(tr);
    });
}

function formatCourseInfo(course, coach, time, location) {
    return `<div class="course-info">
                <div class="course-detail">
                    <i class="fas fa-book"></i> <strong>课程:</strong> ${course}
                </div>
                <div class="course-detail">
                    <i class="fas fa-user"></i> <strong>教练:</strong> ${coach}
                </div>
                <div class="course-detail">
                    <i class="fas fa-clock"></i> <strong>时间:</strong> ${time}
                </div>
                <div class="course-detail">
                    <i class="fas fa-map-marker-alt"></i> <strong>场地:</strong> ${location}
                </div>
            </div>`;
}